<div style="height: 10px; clear: both;"></div>
<div class="row">
	<div class="col s12">
		<h2 class="light-blue-text text-darken-4">
			<i class="fa fa-cube fa-fw" aria-hidden="true"></i> Block 
			<small tooltipped data-position="top" data-tooltip="Unique fingerprint of the block." id="block_hash" style="word-break: break-all; word-wrap: break-word;"></small>
		</h2>
	</div>
</div>
<div class="row">
	<div class="col s12 l8">
		<ul class="collection">
			<li class="collection-item">
				<i class="fas fa-bars fa-fw tooltipped" data-position="top" data-tooltip="Block index in the chain, counting from zero (i.e. genesis block)."></i> 
				Index: <span id="block_index"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-check-double fa-fw tooltipped" data-position="top" data-tooltip="Confirmations, block depth from the tip of the chain."></i> 
				Depth: <span id="block_depth"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-clock fa-fw tooltipped" data-position="top" data-tooltip="Block timestamp displayed as UTC. The timestamp correctness it up to miner, who mined the block."></i> 
				Timestamp: <span id="block_timestamp"></span> &bull; <span id="block_time"></span> (<time id="block-timeago"></time>)
			</li>
			<li class="collection-item">
				<i class="fas fa-link fa-fw tooltipped" data-position="top" data-tooltip="The hash of the previous block."></i> 
				Previous block hash: <a id="prev_hash" title="Previous block"><span id="block_prev_hash"
				style="word-break: break-all; word-wrap: break-word;"></span></a>
			</li>
			<li class="collection-item">
				<i class="fas fa-stamp fa-fw tooltipped" data-position="top" data-tooltip="A piece of data which is difficult (costly, time-consuming) to produce but easy for others to verify and which satisfies certain requirements."></i> 
				Proof of work: <span id="block_pow_hash" style="word-break: break-all; word-wrap: break-word;"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-flag fa-fw tooltipped" data-position="top" data-tooltip="&laquo;major version&raquo;.&laquo;minor version&raquo;"></i>
				Version: <span id="block_version"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-lock-open fa-fw tooltipped" data-position="top" data-tooltip="How difficult it is to find a solution for the block. More specifically, it`s mathematical expectation for number of hashes someone needs to calculate in order to find a correct nonce value solving the block."></i>
				Difficulty: <span id="block_difficulty"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-unlock-alt fa-fw tooltipped" data-position="top" data-tooltip="Cumulative difficulty is the sum of all block's difficulties up to this block including."></i> 
				Cumulative difficulty: <span id="block_cumulative_difficulty"></span>
			</li>
			<li class="collection-item">
			<i class="fas fa-coins fa-fw tooltipped" data-position="top" data-tooltip="Cumulative amount of coins issued by all the blocks in blockchain from the genesis and up to this block."></i>
				Total coins in the network: <span id="block_totalCoins"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-archive fa-fw tooltipped" data-position="top" data-tooltip="Cumulative number of transactions in the blockchain, from the genesis block and up to this block."></i>
				Total transactions in the network: <span id="block_totalTransactions"></span>
			</li>
		</ul>
	</div>
	<div class="col s12 l4">
		<ul class="collection">
			<li class="collection-item">
				<i class="fas fa-code-branch fa-fw tooltipped" data-position="top" data-tooltip="True, if the block belongs to an alternative chain. In such case all the transactions, excluding coinbase, are removed from the block back to transaction pool to be included in another block. It means there is no reward for the miner."></i>
				Orphan: <span id="block_orphan"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-puzzle-piece fa-fw tooltipped" data-position="top" data-tooltip="The nonce a field whose value is adjusted by miners so that the hash of the block will meet difficulty requirement. Any change to the block data (such as the nonce) will make the block hash completely different."></i>
				Nonce: <span id="block_nonce"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-weight-hanging fa-fw tooltipped" data-position="top" data-tooltip="Cumulative size of all transactions in the block, including coinbase. In case it's exceeding 'effective txs median' the reward penalty occurs and therefore miner receives less reward."></i>
				Total transactions size: <span id="block_transactionsSize"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-weight-hanging fa-fw tooltipped" data-position="top" data-tooltip="Size of the whole block, i.e. block header plus all transactions."></i>
				Total block size: <span id="block_blockSize"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-weight-hanging fa-fw tooltipped" data-position="top" data-tooltip="Median value of block total transactions size among last n blocks."></i>
				Current txs median, bytes: <span id="block_currentTxsMedian"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-weight-hanging fa-fw tooltipped" data-position="top" data-tooltip="Bounded from below median value that is actually used to calculate penalty."></i>
				Effective txs median, bytes: <span id="block_effectiveTxsMedian"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-minus-square fa-fw tooltipped" data-position="top" data-tooltip="Penalty for exceeding the median. penalty = (total_transactions_size / effective_tx_median − 1) ^ 2. No penalty if total transactions size is less then effective median. Penalty is near 100% if total txs size is twice the effective median. Greater blocks are not allowed."></i>
				Reward penalty: <span id="block_rewardPenalty"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-trophy fa-fw tooltipped" data-position="top" data-tooltip="Base value for calculating the block reward. Does not depend on how many transactions are included into the block. Also, this is how many coins the miner would receive if the block contains only coinbase transaction."></i>
				Base reward: <span id="block_baseReward"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-donate fa-fw tooltipped" data-position="top" data-tooltip="um of fees for all transactions in the block."></i>
				Transactions fee: <span id="block_transactionsFee"></span>
			</li>
			<li class="collection-item">
				<i class="fas fa-award fa-fw tooltipped" data-position="top" data-tooltip="Actual amount of coins the miner received for finding the block: reward = base_reward × (1 − penalty) + transactions_fees"></i>
				Reward: <span id="block_reward"></span>
			</li>
		</ul>
	</div>
				
</div>
<div class="row">
	<div class="col s12">
		<div class="card hoverable">
			<div class="card-action grey lighten-5">
				<h3 class="light-blue-text text-darken-4">
					<i class="fas fa-exchange-alt tooltipped" data-position="top" 
					data-tooltip="Number of transactions in the block, including coinbase transaction (which transfers block reward to the miner)."></i> 
					Тransactions <span class="badge light-blue darken-3 white-text" id="block_transactions"></span></h3>
			</div>
			<div class="card-content">
				<div class="row">
					<div class="col s12 table-responsive">
						<table class="highlight centered">
							<thead>
								<tr>
									<th>№</th>
									<th><i class="fa fa-paw"></i> Hash</th>
									<th><i class="fas fa-donate"></i> Fee</th>
									<th><i class="fas fa-money-bill"></i> Total Amount</th>
									<th><i class="fas fa-weight-hanging"></i> Size</th>
								</tr>
							</thead>
							<tbody id="transactions_rows">
					
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>


<script>
	var block, xhrGetBlock;
	var refresh, next = false;

	currentPage = {
		destroy: function () {
			if (xhrGetBlock) xhrGetBlock.abort();
		},
		init: function () {
			$('.tooltipped').tooltip();
		},
		update: function () {
			getBlock();
		}
	};

	function getBlock() {
		if (xhrGetBlock) xhrGetBlock.abort();
		var searchBlk = $.parseJSON(sessionStorage.getItem('searchBlock'));
		if (searchBlk) {
			renderBlock(searchBlk);
		} else {
			xhrGetBlock = $.ajax({
				url: api + '/json_rpc',
				method: "POST",
				data: JSON.stringify({
					jsonrpc: "2.0",
					id: "explorer_block_page",
					method: "getblockbyhash",
					params: {
						hash: urlParam('hash')
					}
				}),
				dataType: 'json',
				cache: 'false',
				success: function (data) {
					block = data.result.block;
					renderBlock(block);
				}
			});
		}
		sessionStorage.removeItem('searchBlock');
	}

	function renderBlock(block) {
		updateText('block_hash', block.hash);
		updateText('block_depth', block.depth);
		updateText('block_prev_hash', block.prevBlockHash);
		updateText('block_pow_hash', block.proofOfWork);
		document.getElementById('prev_hash').setAttribute('href', getBlockchainUrl(block.prevBlockHash));
		updateText('block_timestamp', block.timestamp);
		updateText('block_time', formatDate(block.timestamp));
		$("#block-timeago").timeago('update', new Date(block.timestamp * 1000).toISOString());
		updateText('block_version', block.majorVersion + '.' + block.minorVersion);
		updateText('block_nonce', block.nonce);
		updateText('block_cumulative_difficulty', block.cumulativeDifficulty);
		updateText('block_difficulty', block.difficulty);
		updateText('block_orphan', block.isOrphaned ? "Yes" : "No");
		$("#block_orphan").addClass(block.isOrphaned ? "red-text" : "green-text");
		updateText('block_transactions', block.transactions.length);
		updateText('block_transactionsSize', formatBytes(parseInt(block.transactionsCumulativeSize)));
		updateText('block_blockSize', formatBytes(parseInt(block.blockSize)));
		updateText('block_currentTxsMedian', formatBytes(parseInt(block.sizeMedian)));
		updateText('block_effectiveTxsMedian', formatBytes(parseInt(block.effectiveSizeMedian)));
		updateText('block_rewardPenalty', block.penalty * 100 + "%");
		updateText('block_baseReward', getReadableCoins(block.baseReward));
		updateText('block_transactionsFee', getReadableCoins(block.totalFeeAmount));
		updateText('block_reward', getReadableCoins(block.reward));
		updateText('block_totalCoins', getReadableCoins(block.alreadyGeneratedCoins));
		updateText('block_totalTransactions', block.alreadyGeneratedTransactions);
		renderTransactions(block.transactions);

		// if this block is orphan make its height a link to the main chain block
		if (!refresh)
			if (block.isOrphaned) {
				var m_block, xhrGetSearchBlockbyHeight;
				if (xhrGetSearchBlockbyHeight) xhrGetSearchBlockbyHeight.abort();

				xhrGetSearchBlockbyHeight = $.ajax({
					url: api + '/json_rpc',
					method: "POST",
					data: JSON.stringify({
						jsonrpc: "2.0",
						id: "explorer_block_page",
						method: "getblockheaderbyheight",
						params: {
							height: block.index
						}
					}),
					dataType: 'json',
					cache: 'false',
					success: function (data) {
						if (data.result) {
							m_block = data.result.block_header;
							$('#block_index').append(' <a href="' + getBlockchainUrl(m_block.hash) +
								'" title="Main chain block">' + block.index + '</a>');
						}
					}
				});
			} else {
				$('#block_index').text(block.index);
			}

		if (!refresh) {
			makePrevBlockLink(block.prevBlockHash);
		}

		$.ajax({
			url: api + '/json_rpc',
			method: "POST",
			data: JSON.stringify({
				jsonrpc: "2.0",
				id: "explorer_block_page",
				method: "getblockheaderbyheight",
				params: {
					height: (block.index + 1)
				}
			}),
			dataType: 'json',
			cache: 'false',
			success: function (data) {
				if (data.result) {
					var nextBlockHash = data.result.block_header.hash;
				}
				if (nextBlockHash && !next) {
					makeNextBlockLink(nextBlockHash);
					next = true;
				}
			},
			error: function (ajaxContext) {}
		});
		refresh = true;
	}

	function getTransactionCells(transaction) {
		return '<td>' + '</td>' +
			'<td>' + formatPaymentLink(transaction.hash) + '</td>' +
			'<td>' + getReadableCoins(transaction.fee, 4, true) + '</td>' +
			'<td>' + getReadableCoins(transaction.totalOutputsAmount, 4, true) + '</td>' +
			'<td>' + formatBytes(parseInt(transaction.size)) + '</td>';
	}

	function getTransactionRowElement(transaction, jsonString) {
		var row = document.createElement('tr');
		row.setAttribute('data-json', jsonString);
		row.setAttribute('data-hash', transaction.hash);
		row.setAttribute('id', 'transactionRow' + transaction.hash);
		row.innerHTML = getTransactionCells(transaction);
		return row;
	}

	function renderTransactions(transactionResults) {
		var $transactionsRows = $('#transactions_rows');
		for (var i = 0; i < transactionResults.length; i++) {
			var transaction = transactionResults[i];
			var transactionJson = JSON.stringify(transaction);
			var existingRow = document.getElementById('transactionRow' + transaction.hash);
			if (existingRow && existingRow.getAttribute('data-json') !== transactionJson) {
				$(existingRow).replaceWith(getTransactionRowElement(transaction, transactionJson));
			} else if (!existingRow) {
				var transactionElement = getTransactionRowElement(transaction, transactionJson);
				$transactionsRows.append(transactionElement);
			}
			$(transactionElement).find("td:first").html(i);
		}
	}

	function makeNextBlockLink(blockHash) {
		$('#block_index').append(' <a href="' + getBlockchainUrl(blockHash) +
			'" title="Next block"><i class="fa fa-chevron-circle-right ooltipped" data-position="top" data-tooltip="Next block"" aria-hidden="true"></i></a>');
	}

	function makePrevBlockLink(blockHash) {
		$('#block_index').prepend('<a href="' + getBlockchainUrl(blockHash) +
			'" title="Previous block"><i class="fa fa-chevron-circle-left tooltipped" data-position="top" data-tooltip="Previous block" aria-hidden="true"></i></a> ');
	}

	function formatPrevNextBlockLink(hash) {
		return '<a href="' + getBlockchainUrl(hash) + '">' + hash + '</a>';
	}

</script>